package com.share.filter;

import com.share.entity.User;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by leep on 2015-12-30.
 */
public class ServletFilter implements Filter {
	List<String> whiteUrls;

	public void init(FilterConfig filterConfig) throws ServletException {
		whiteUrls = new ArrayList<String>();
		whiteUrls.add("/login");
		whiteUrls.add("/register");
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		response.setContentType("text/html; charset=utf8");
		request.setCharacterEncoding("utf8");
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		if (user == null && !isWhiteUrl(request.getServletPath())) {
			response.sendRedirect("/login");
		} else if (user != null && isWhiteUrl(request.getServletPath())) {
			response.sendRedirect("/user");
		} else {
			filterChain.doFilter(request, response);
		}

	}

	public void destroy() {

	}

	public boolean isWhiteUrl(String curUrl) {
		boolean result = false;
		for (String url : whiteUrls) {
			if (StringUtils.equals(url, curUrl)) {
				result = true;
				break;
			}
		}

		return result;
	}
}
